package com.example.blog.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.blog.entity.BlogType;
import com.example.blog.service.TypeService;
import com.example.blog.utils.Result;

@RestController
@RequestMapping("/api/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    // 获取所有类型
    @GetMapping("/list")
    public Result<List<BlogType>> getAllTypes() {
        try {
            List<BlogType> types = typeService.getAllTypes();
            return Result.success(types);
        } catch (Exception e) {
            return Result.error("获取类型列表失败：" + e.getMessage());
        }
    }

    // 根据ID获取类型
    @GetMapping("/{id}")
    public Result<BlogType> getTypeById(@PathVariable("id") Integer typeId) {
        try {
            BlogType type = typeService.getTypeById(typeId);
            if (type == null) {
                return Result.error("类型不存在");
            }
            return Result.success(type);
        } catch (Exception e) {
            return Result.error("获取类型失败：" + e.getMessage());
        }
    }

    // 创建新类型
    @PostMapping("/create")
    public Result<BlogType> createType(@RequestBody BlogType blogType, @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            Integer userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            blogType.setUserId(userId);
            BlogType newType = typeService.createType(blogType);
            return Result.success(newType);
        } catch (Exception e) {
            return Result.error("创建类型失败：" + e.getMessage());
        }
    }

    // 更新类型
    @PutMapping("/update/{id}")
    public Result<BlogType> updateType(@PathVariable("id") Integer typeId, 
                                     @RequestBody BlogType blogType,
                                     @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            Integer userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            blogType.setUserId(userId);
            blogType.setTypeId(typeId);
            
            BlogType updatedType = typeService.updateType(blogType);
            return Result.success(updatedType);
        } catch (Exception e) {
            return Result.error("更新类型失败：" + e.getMessage());
        }
    }

    // 删除类型
    @DeleteMapping("/delete/{id}")
    public Result<Void> deleteType(@PathVariable("id") Integer typeId,
                                 @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取用户ID
            Integer userId = getUserIdFromToken(token);
            if (userId == null) {
                return Result.error("未登录或登录已过期");
            }
            
            boolean success = typeService.deleteType(typeId);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除类型失败");
            }
        } catch (Exception e) {
            return Result.error("删除类型失败：" + e.getMessage());
        }
    }

    // 从token中获取用户ID
    private Integer getUserIdFromToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return null;
        }
        
        // 移除"Bearer "前缀
        String actualToken = token.substring(7);
        
        // TODO: 实现token解析逻辑
        // 这里需要根据你的token生成规则来实现
        // 例如：如果token格式为 "user_123"，则返回123
        try {
            if (actualToken.startsWith("user_")) {
                return Integer.parseInt(actualToken.substring(5));
            }
        } catch (NumberFormatException e) {
            return null;
        }
        
        return null;
    }
} 